package com.lesson20.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.lesson20.model.StudentModel;

@RestController
public class StudentController {
	
	private Map<Integer, StudentModel> stus = new HashMap<>();
	
	@RequestMapping(value={"/stu/login"})
	public Map<String, Object> login(HttpServletRequest request, HttpServletResponse response,  String userName, String password){
		Map<String, Object> results = new HashMap<String, Object>();
		if(StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)){
			results.put("code", "000001");
			 results.put("msg", "fail");
			return results;
		}
		Cookie cookie = new Cookie("loginToken", UUID.randomUUID().toString());
		response.addCookie(cookie);
		results.put("code", "000000");
		results.put("msg", "success");
		return results;
	}
	
	
	@RequestMapping(value={"/stu/addStudent"})
	public Map<String, Object> addStudent(HttpServletRequest request, StudentModel studentModel){
		Map<String, Object> results = new HashMap<String, Object>();
		 results.put("code", "000000");
		 results.put("msg", "success");
		 stus.put(studentModel.getId(), studentModel);
		 System.out.println("UserName = "+studentModel.getUserName());
		 System.out.println("loginToken = "+ studentModel.getLoginToken());
		 
		 Cookie[] cookie = request.getCookies();
		 for(int i=0; i<cookie.length; i++){
			 System.out.println("name = "+cookie[i].getName() +", vaule = "+cookie[i].getValue());
		 }
		 
		 return results; 
	}
	
	@RequestMapping(value={"/stu/getStudent"})
	public StudentModel getStudent(StudentModel studentModel){
		 System.out.println(stus);
		 return stus.get(studentModel.getId()); 
	}

}
